package com.afdor.rws.event.channel.local.consumer;

import com.afdor.rws.annotation.extension.Extension;
import com.afdor.rws.event.channel.client.consumer.AbstractEventConsumer;
import com.afdor.rws.event.channel.client.consumer.EventConsumer;
import com.afdor.rws.event.channel.local.LocalObserverEventListener;
import com.afdor.rws.event.channel.local.observer.ObserverEventSource;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

/**
 * 本地事件消费者
 *
 * @author 悭梵
 * @date Created in 2018-08-08 10:59
 */
@Slf4j
@ToString
@EqualsAndHashCode
@NoArgsConstructor
@Extension(value = "local", order = Extension.NORMAL_ORDER - 100, scope = Extension.Scope.PROTOTYPE, interfaceClass = EventConsumer.class)
public class LocalEventConsumer extends AbstractEventConsumer {

    private ObserverEventSource eventSource;

    public LocalEventConsumer(ObserverEventSource eventSource) {
        super();
        setEventSource(eventSource);
    }

    @Override
    public void start() {
        this.eventSource.addEventListener(getEventSourceName(), new LocalObserverEventListener(this));
        super.start();
    }

    @Override
    public void stop() {
        this.eventSource.clearEventListener();
        super.stop();
    }

    public void setEventSource(ObserverEventSource eventSource) {
        this.eventSource = Optional.ofNullable(eventSource).orElseThrow(() -> new IllegalArgumentException("事件发生管理容器为空"));
    }

    @Override
    protected boolean hasEvent() {
        return this.eventSource.hasEvent();
    }

    @Override
    protected boolean consume() {
        // TODO 执行重试策略
        return this.eventSource.consume();
    }


}
